package com.example.buletooth_spp;

import static java.lang.Float.parseFloat;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

@SuppressLint("UseSwitchCompatOrMaterialCode")
public class UiData {

    private EditText editText;

    private Switch switchLight;

    private SeekBar seekBarFanSpeed;
    private SeekBar seekBarRangeHoodSpeed;
    private EditText fanSpeed;
    private EditText rangeHoodSpeed;

    private TextView curTem;
    private TextView curHum;
    private TextView curMQ2;
    private TextView curMQ135;

    private Switch temWarningFlag;
    private Switch humWarningFlag;
    private Switch mq2WarningFlag;
    private Switch mq135WarningFlag;

    private EditText temWarningData;
    private EditText humWarningData;
    private EditText mq2WarningData;
    private EditText mq135WarningData;

    private MainActivity activity;
    private RecDataFrame recDataFrame;
    private SendDataFrame sendDataFrame;

    private boolean flag = true;
    private boolean fanPermitUpdate = true;
    private boolean rangeHoodPermitUpdate = true;

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            // 从消息中获取数据并更新 UI
            byte[] receivedData = (byte[]) msg.obj;
            String data = new String(receivedData);
            unPack(data);
            updateUi();
            getEditText().setText(data);
        }
    };

    public UiData(MainActivity activity) {
        this.activity = activity;
        this.recDataFrame = new RecDataFrame();
        this.sendDataFrame = new SendDataFrame();

        this.initUi();
    }

    private void initUi() {
        this.switchLight = this.activity.findViewById(R.id.switch_LightFlag);
        this.seekBarFanSpeed = this.activity.findViewById(R.id.seekBar_Fan_Speed);
        this.seekBarRangeHoodSpeed = this.activity.findViewById(R.id.seekBar_RangeHood_Speed);
        this.fanSpeed = this.activity.findViewById(R.id.text_Fan_Speed_data);
        this.rangeHoodSpeed = this.activity.findViewById(R.id.text_RangeHood_Speed_data);
        this.curTem = this.activity.findViewById(R.id.text_tem_data);
        this.curHum = this.activity.findViewById(R.id.text_hum_data);
        this.curMQ2 = this.activity.findViewById(R.id.text_mq2_data);
        this.curMQ135 = this.activity.findViewById(R.id.text_mq135_data);
        this.temWarningFlag = this.activity.findViewById(R.id.switch_TemWarningFlag);
        this.humWarningFlag = this.activity.findViewById(R.id.switch_HumWarningFlag);
        this.mq2WarningFlag = this.activity.findViewById(R.id.switch_MQ2WarningFlag);
        this.mq135WarningFlag = this.activity.findViewById(R.id.switch_MQ135WarningFlag);
        this.temWarningData = this.activity.findViewById(R.id.edit_tem_warning);
        this.humWarningData = this.activity.findViewById(R.id.edit_hum_warning);
        this.mq2WarningData = this.activity.findViewById(R.id.edit_mq2_warning);
        this.mq135WarningData = this.activity.findViewById(R.id.edit_mq135_warning);
        this.editText = this.activity.findViewById(R.id.editTextText2);

        this.setAllDeviceIsEnable(false);

        this.seekBarFanSpeed.setMin(-500);
        this.seekBarFanSpeed.setMax(500);
        this.seekBarRangeHoodSpeed.setMin(-500);
        this.seekBarRangeHoodSpeed.setMax(500);
    }

    public short checkedNumInRange(short num, short r1, short r2)
    {
        if(num < r1)
            return r1;
        else if(num > r2)
            return r2;
        else
            return num;
    }

    //将接收帧中的数据 更新到 发送帧中
    public void recDataFrameToSendDataFrame()
    {
        this.sendDataFrame.setLightFlag((byte) (this.recDataFrame.getLightState() ? 1 : 0));
        this.sendDataFrame.setFanSpeed((short) this.recDataFrame.getFanSpeed());
        this.sendDataFrame.setRangeHoodSpeed((short) this.recDataFrame.getRangeHoodSpeed());
        this.sendDataFrame.setWarningOpenFlags(this.booleanToByte(this.recDataFrame.getWarningOpenFlags()));
        this.sendDataFrame.setWarningNums(this.recDataFrame.getWarningNums());
    }

    private byte[] booleanToByte(boolean [] arr)
    {
        byte[] tem = new byte[arr.length];
        for (int i = 0; i < arr.length; i++) {
            tem[i] = (byte) (arr[i] ? 1 : 0);
        }

        return tem;
    }

    public void setAllDeviceIsEnable(boolean flag)
    {
        switchLight            .setEnabled(flag);
        seekBarFanSpeed        .setEnabled(flag);
        seekBarRangeHoodSpeed  .setEnabled(flag);
        fanSpeed               .setEnabled(flag);
        rangeHoodSpeed         .setEnabled(flag);
        curTem                 .setEnabled(flag);
        curHum                 .setEnabled(flag);
        curMQ2                 .setEnabled(flag);
        curMQ135               .setEnabled(flag);
        temWarningFlag         .setEnabled(flag);
        humWarningFlag         .setEnabled(flag);
        mq2WarningFlag         .setEnabled(flag);
        mq135WarningFlag       .setEnabled(flag);
        temWarningData         .setEnabled(flag);
        humWarningData         .setEnabled(flag);
        mq2WarningData         .setEnabled(flag);
        mq135WarningData       .setEnabled(flag);
    }

    //问题：报警值输入可能会闪退
    void startListener()
    {
        this.switchLight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if(!compoundButton.isPressed())
                    return;

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                sendDataFrame.setLightFlag((byte)(b ? 1 : 0));

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());
                //PrintTip.printInfo(activity, sendDataFrame.getLightFlag() + "");
            }
        });

        this.seekBarFanSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 更新 TextView 的内容为当前进度值
                fanSpeed.setText(String.format("%d", progress));
                fanPermitUpdate = false;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {     //开始拖动时触发

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {      //用户停止触摸时触发
                fanPermitUpdate = true;
                int value = seekBar.getProgress();

                recDataFrameToSendDataFrame();                      //更新数据

                //将控件中的数据更新到发送帧中
                sendDataFrame.setFanSpeed((short) value);

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());
            }
        });

        this.fanSpeed.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE ||
                    (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) {
                String input = fanSpeed.getText().toString();
                //按下完成/换行触发

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                try {
                    short value = Short.parseShort(input);

                    sendDataFrame.setFanSpeed(checkedNumInRange(value, (short) -500, (short) 500));
                }
                catch (Exception e)
                {
                    PrintTip.printInfo(activity, "请输入有效的参数");
                }

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());

                fanPermitUpdate = true;

                return true; // 返回 true 表示已处理该事件
            }
            return false;
        });

        this.seekBarRangeHoodSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 更新 TextView 的内容为当前进度值
                rangeHoodSpeed.setText(String.format("%d", progress));
                rangeHoodPermitUpdate = false;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                rangeHoodPermitUpdate = true;
                int value = seekBar.getProgress();

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                sendDataFrame.setRangeHoodSpeed((short) value);

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());
                //PrintTip.printInfo(activity, value + "");
            }
        });

        this.rangeHoodSpeed.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE ||
                    (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) {
                String input = rangeHoodSpeed.getText().toString();
                //按下完成/换行触发

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                try {
                    short value = Short.parseShort(input);
                    sendDataFrame.setRangeHoodSpeed(checkedNumInRange(value, (short) -500, (short) 500));
                }
                catch (Exception e)
                {
                    PrintTip.printInfo(activity, "请输入有效的参数");
                }

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());

                rangeHoodPermitUpdate = true;

                return true; // 返回 true 表示已处理该事件
            }
            return false;
        });

        this.temWarningFlag.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(!compoundButton.isPressed())
                    return;

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                sendDataFrame.getWarningOpenFlags()[0] = (byte)(b ? 1 : 0);

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());
                //PrintTip.printInfo(activity, sendDataFrame.getLightFlag() + "");
            }
        });

        this.humWarningFlag.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(!compoundButton.isPressed())
                    return;

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                sendDataFrame.getWarningOpenFlags()[1] = (byte)(b ? 1 : 0);

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());
                //PrintTip.printInfo(activity, sendDataFrame.getLightFlag() + "");
            }
        });

        this.mq2WarningFlag.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(!compoundButton.isPressed())
                    return;

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                sendDataFrame.getWarningOpenFlags()[2] = (byte)(b ? 1 : 0);

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());
                //PrintTip.printInfo(activity, sendDataFrame.getLightFlag() + "");
            }
        });

        this.mq135WarningFlag.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(!compoundButton.isPressed())
                    return;

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                sendDataFrame.getWarningOpenFlags()[3] = (byte)(b ? 1 : 0);

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());
                //PrintTip.printInfo(activity, sendDataFrame.getLightFlag() + "");
            }
        });

        this.temWarningData.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE ||
                    (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) {
                String input = temWarningData.getText().toString();
                //按下完成/换行触发

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                float value = parseFloat(input);
                sendDataFrame.getWarningNums()[0] = (value > 500 ? 500.0f : value);

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());

                //PrintTip.printInfo(activity, temWarningData.getText().toString());

                return true; // 返回 true 表示已处理该事件
            }
            return false;
        });

        this.humWarningData.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE ||
                    (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) {
                String input = humWarningData.getText().toString();

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                float value = parseFloat(input);
                sendDataFrame.getWarningNums()[1] = (value > 500 ? 500.0f : value);

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());

                return true; // 返回 true 表示已处理该事件
            }
            return false;
        });

        this.mq2WarningData.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE ||
                    (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) {
                String input = mq2WarningData.getText().toString();

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                float value = parseFloat(input);
                sendDataFrame.getWarningNums()[2] = (value > 1000 ? 1000 : value);

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());

                //PrintTip.printInfo(activity, temWarningData.getText().toString());

                return true; // 返回 true 表示已处理该事件
            }
            return false;
        });

        this.mq135WarningData.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE ||
                    (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) {
                String input = mq135WarningData.getText().toString();

                recDataFrameToSendDataFrame();      //更新数据

                //将控件中的数据更新到发送帧中
                float value = parseFloat(input);
                sendDataFrame.getWarningNums()[3] = (value > 1000 ? 1000 : value);

                activity.getBlueTooth().bluetoothSendPack(sendDataFrame.pack());

                //PrintTip.printInfo(activity, temWarningData.getText().toString());

                return true; // 返回 true 表示已处理该事件
            }
            return false;
        });
    }

    public void updateUi()
    {
        this.switchLight            .setChecked(this.getRecDataFrame().getLightState());

        if (this.fanPermitUpdate)
            this.seekBarFanSpeed        .setProgress(this.getRecDataFrame().getFanSpeed());

        if (this.rangeHoodPermitUpdate)
            this.seekBarRangeHoodSpeed  .setProgress(this.getRecDataFrame().getRangeHoodSpeed());
        //this.fanSpeed               .setText(String.format("%d", this.getRecDataFrame().getFanSpeed()));
        //this.rangeHoodSpeed         .setText(String.format("%d", this.getRecDataFrame().getRangeHoodSpeed()));

        this.curTem                 .setText(String.valueOf(this.getRecDataFrame().getCurNums()[0]));
        this.curHum                 .setText(String.valueOf(this.getRecDataFrame().getCurNums()[1]));
        this.curMQ2                 .setText(String.valueOf(this.getRecDataFrame().getCurNums()[2]));
        this.curMQ135               .setText(String.valueOf(this.getRecDataFrame().getCurNums()[3]));

        this.temWarningFlag         .setChecked(this.getRecDataFrame().getWarningOpenFlags()[0]);
        this.humWarningFlag         .setChecked(this.getRecDataFrame().getWarningOpenFlags()[1]);
        this.mq2WarningFlag         .setChecked(this.getRecDataFrame().getWarningOpenFlags()[2]);
        this.mq135WarningFlag       .setChecked(this.getRecDataFrame().getWarningOpenFlags()[3]);

        if(!this.fanSpeed.isFocused())
        {
            this.fanSpeed.setText(String.valueOf(getRecDataFrame().getFanSpeed()));
        }
        if(!this.rangeHoodSpeed.isFocused()) {
            this.rangeHoodSpeed.setText(String.valueOf(getRecDataFrame().getRangeHoodSpeed()));
        }

        if (!this.temWarningData.isFocused())
            temWarningData.setText(String.valueOf(getRecDataFrame().getWarningNums()[0]));
        if (!this.humWarningData.isFocused())
            humWarningData.setText(String.valueOf(getRecDataFrame().getWarningNums()[1]));
        if (!this.mq2WarningData.isFocused())
            mq2WarningData.setText(String.valueOf(getRecDataFrame().getWarningNums()[2]));
        if (!this.mq135WarningData.isFocused())
            mq135WarningData.setText(String.valueOf(getRecDataFrame().getWarningNums()[3]));

        if(flag)
        {
            this.seekBarFanSpeed        .setProgress(this.getRecDataFrame().getFanSpeed());
            this.seekBarRangeHoodSpeed  .setProgress(this.getRecDataFrame().getRangeHoodSpeed());
            this.temWarningData         .setText(String.valueOf(getRecDataFrame().getWarningNums()[0]));
            this.humWarningData         .setText(String.valueOf(this.getRecDataFrame().getWarningNums()[1]));
            this.mq2WarningData         .setText(String.valueOf(this.getRecDataFrame().getWarningNums()[2]));
            this.mq135WarningData       .setText(String.valueOf(this.getRecDataFrame().getWarningNums()[3]));
            flag = false;
        }
    }

    public void unPack(String recData)
    {
        // 使用 split 方法分割字符串
        String[] params = recData.split(",");

        // 提取每个参数并转换为合适的类型
        this.recDataFrame.setLightState(Integer.parseInt(params[0].trim()) != 1);
        this.recDataFrame.setFanSpeed(Integer.parseInt(params[1].trim()));
        this.recDataFrame.setRangeHoodSpeed(Integer.parseInt(params[2].trim()));
        this.recDataFrame.getCurNums()[0] = parseFloat(params[3].trim());
        this.recDataFrame.getCurNums()[1] = parseFloat(params[4].trim());
        this.recDataFrame.getCurNums()[2] = parseFloat(params[5].trim());
        this.recDataFrame.getCurNums()[3] = parseFloat(params[6].trim());
        this.recDataFrame.getWarningOpenFlags()[0] = Integer.parseInt(params[7].trim()) == 1;
        this.recDataFrame.getWarningOpenFlags()[1] = Integer.parseInt(params[8].trim()) == 1;
        this.recDataFrame.getWarningOpenFlags()[2] = Integer.parseInt(params[9].trim()) == 1;
        this.recDataFrame.getWarningOpenFlags()[3] = Integer.parseInt(params[10].trim()) == 1;
        this.recDataFrame.getWarningNums()[0] = parseFloat(params[11].trim());
        this.recDataFrame.getWarningNums()[1] = parseFloat(params[12].trim());
        this.recDataFrame.getWarningNums()[2] = parseFloat(params[13].trim());
        this.recDataFrame.getWarningNums()[3] = parseFloat(params[14].trim());
    }

//    byte[] pack(MainActivity activity)
//    {
////        ByteBuffer buffer = ByteBuffer.allocate(32);
////        buffer.put(activity.getSwitchLight().ch);                               //灯
////        buffer.putShort((short) -500);                      //风扇转速
////        buffer.putShort((short) -500);                      //风机转速
////        buffer.put((byte) 1);                               //温度报警flag
////        buffer.put((byte) 1);                               //湿度报警flag
////        buffer.put((byte) 1);                               //燃气报警flag
////        buffer.put((byte) 1);                               //烟雾报警flag
////        buffer.put(convertFloatToHalfFloat(60.1f));         //温度报警阈值
////        buffer.put(convertFloatToHalfFloat(90.1f));         //湿度报警阈值
////        buffer.put(convertFloatToHalfFloat(6.1f));          //燃气报警阈值
////        buffer.put(convertFloatToHalfFloat(6.1f));          //烟雾报警阈值
////        blueTooth.bluetoothSendPack(buffer.array());
//    }

    public Handler getHandler() {
        return handler;
    }

    public RecDataFrame getRecDataFrame() {
        return recDataFrame;
    }

    public EditText getEditText() {
        return editText;
    }

    public Switch getSwitchLight() {
        return switchLight;
    }

    public SeekBar getSeekBarFanSpeed() {
        return seekBarFanSpeed;
    }

    public SeekBar getSeekBarRangeHoodSpeed() {
        return seekBarRangeHoodSpeed;
    }

    public TextView getCurTem() {
        return curTem;
    }

    public TextView getCurHum() {
        return curHum;
    }

    public TextView getCurMQ2() {
        return curMQ2;
    }

    public TextView getCurMQ135() {
        return curMQ135;
    }

    public Switch getTemWarningFlag() {
        return temWarningFlag;
    }

    public Switch getHumWarningFlag() {
        return humWarningFlag;
    }

    public Switch getMq2WarningFlag() {
        return mq2WarningFlag;
    }

    public Switch getMq135WarningFlag() {
        return mq135WarningFlag;
    }

    public EditText getTemWarningData() {
        return temWarningData;
    }

    public EditText getHumWarningData() {
        return humWarningData;
    }

    public EditText getMq2WarningData() {
        return mq2WarningData;
    }

    public EditText getMq135WarningData() {
        return mq135WarningData;
    }

    public SendDataFrame getSendDataFrame() {
        return sendDataFrame;
    }

    public AppCompatActivity getActivity() {
        return activity;
    }
}
